package io.zcoder.innoway.activities;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;

import com.crashlytics.android.Crashlytics;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterAuthClient;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.zcoder.innoway.R;
import io.zcoder.innoway.commons.PrefUtils;
import io.zcoder.innoway.models.DataUser;
import io.zcoder.innoway.models.UserResponse;
import io.zcoder.innoway.rest.RestClient;
import io.zcoder.innoway.widgets.EditTextCustom;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class LoginActivity extends BaseActivity {
    CallbackManager callbackManager;
    TwitterAuthClient client;
    @BindView(R.id.email)
    EditTextCustom mEditEmail;

    @BindView(R.id.password)
    EditTextCustom mEditPass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        client = new TwitterAuthClient();
        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        // App code
                        showProgress();
                        Log.d("Facebook", loginResult.getAccessToken().getToken());
                        RestClient.build(LoginActivity.this, false).loginBy(0, loginResult.getAccessToken().getToken(), "", new Callback<UserResponse>() {
                            @Override
                            public void success(UserResponse userResponse, Response response) {
                                saveUserInfo(userResponse.getData());
                                hideProgress();
                            }

                            @Override
                            public void failure(RetrofitError error) {
                                hideProgress();
                                showAlert(getString(R.string.error), error.getMessage());
                            }
                        });
                    }

                    @Override
                    public void onCancel() {
                        // App code
                        Log.d("Facebook", "onCancel");
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        // App code
                        Log.d("Facebook", "onError" + exception.getLocalizedMessage());
                    }
                });
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
       
    }


    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
        client.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick(R.id.btn_back)
    void back() {
        finish();
    }

    @OnClick(R.id.join)
    void loginSignIn() {
        String email = mEditEmail.getText().toString();
        String password = mEditPass.getText().toString();
        if (password.length() > 6 || password.length() < 1 ) {
            showAlert(getString(R.string.error), getString(R.string.error_pass));
            return;
        }
        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            showAlert(getString(R.string.error), getString(R.string.error_email));
            return;
        }
        showProgress();
        RestClient.build(this, false).login(email, password, new Callback<UserResponse>() {
            @Override
            public void success(UserResponse userResponse, Response response) {
                hideProgress();
                if (userResponse.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), userResponse.getMessage());
                    return;
                }
                saveUserInfo(userResponse.getData());

            }

            @Override
            public void failure(RetrofitError error) {
                hideProgress();
                showAlert(getString(R.string.error), error.getMessage());
            }
        });
    }

    private void saveUserInfo(DataUser data) {
        PrefUtils.setString(LoginActivity.this, PrefUtils.PREF_AUTHEN_TOKEN, data.getAuth_token());
        if (data.getProfiles() != null && !data.getProfiles().isEmpty()) {
            PrefUtils.setInt(LoginActivity.this, PrefUtils.PREF_USER_ID, data.getProfiles().get(0).getUser_id());
            PrefUtils.setInt(LoginActivity.this, PrefUtils.PREF_PROFILE_ID, data.getProfiles().get(0).getId());
        }
        logUser(data);
        finish();
        Intent intent = new Intent(LoginActivity.this, TopActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @OnClick(R.id.txt_forgot_password)
    void loginForgotPassword() {
        Intent intent = new Intent(this, ForgotPasswordActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.btn_login_facebook)
    void loginFacebook() {
        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
    }

    @OnClick(R.id.btn_login_twitter)
    void loginTwitter() {
        client.authorize(this, new com.twitter.sdk.android.core.Callback<TwitterSession>() {
            @Override
            public void success(Result<TwitterSession> result) {
                TwitterSession data = result.data;
                RestClient.build(LoginActivity.this, false).loginBy(1, data.getAuthToken().token, data.getAuthToken().secret, new Callback<UserResponse>() {
                    @Override
                    public void success(UserResponse userResponse, Response response) {
                        saveUserInfo(userResponse.getData());
                        hideProgress();
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        hideProgress();
                        showAlert(getString(R.string.error), error.getMessage());
                    }
                });
            }

            @Override
            public void failure(TwitterException exception) {
                showAlert(getString(R.string.error), exception.getLocalizedMessage());
            }
        });
    }


    private void logUser(DataUser data) {
        // You can call any combination of these three methods
        Crashlytics.setUserIdentifier(data.getId() +"");
        Crashlytics.setUserEmail(data.getEmail());
        Crashlytics.setUserName(data.getProfiles().get(0).getFirst_name() + " " + data.getProfiles().get(0).getLast_name());
    }


}
